<template>
  <div class="assignment-grading">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>作业批改</h2>
          <div class="student-info">
            <span>学生：{{ submission.studentName }}</span>
            <span>提交时间：{{ formatDate(submission.submitTime) }}</span>
          </div>
        </div>
      </template>

      <div class="submission-content">
        <div class="content-header">
          <h3>作业内容</h3>
          <el-button
            type="warning"
            size="small"
            :loading="checkingPlagiarism"
            @click="checkPlagiarism"
          >
            查重分析
          </el-button>
        </div>
        
        <el-collapse v-if="plagiarismResult" class="plagiarism-result">
          <el-collapse-item>
            <template #title>
              <span>
                查重结果：
                <span :class="getSimilarityClass(plagiarismResult.similarity)">
                  {{ (plagiarismResult.similarity * 100).toFixed(1) }}% 相似度
                </span>
              </span>
            </template>
            <div v-if="plagiarismResult.matchedSubmissions.length" class="matched-submissions">
              <div
                v-for="match in plagiarismResult.matchedSubmissions"
                :key="match.submissionId"
                class="matched-item"
              >
                <div class="match-header">
                  <span>学生：{{ match.studentName }}</span>
                  <span>相似度：{{ (match.similarity * 100).toFixed(1) }}%</span>
                </div>
                <div class="matched-content">
                  <pre>{{ match.matchedContent }}</pre>
                </div>
              </div>
            </div>
            <div v-else>
              未发现明显相似内容
            </div>
          </el-collapse-item>
        </el-collapse>

        <div class="content-text">{{ submission.content }}</div>

        <div v-if="submission.attachments?.length" class="attachments">
          <div class="attachments-header">
            <h4>附件</h4>
            <el-button
              type="primary"
              size="small"
              @click="downloadAllAttachments"
            >
              批量下载
            </el-button>
          </div>
          <el-button
            v-for="file in submission.attachments"
            :key="file.url"
            type="primary"
            link
            @click="downloadFile(file)"
          >
            {{ file.name }}
          </el-button>
        </div>
      </div>

      <el-form :model="gradingForm" label-width="100px" @submit.prevent="submitGrade">
        <el-form-item label="分数" required>
          <el-input-number
            v-model="gradingForm.score"
            :min="0"
            :max="100"
            :precision="0"
          />
        </el-form-item>

        <el-form-item label="评语" required>
          <el-input
            v-model="gradingForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入评语"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="submitting">
            提交评分
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { format } from 'date-fns'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import { checkPlagiarism, type PlagiarismResult } from '@/api/plagiarismCheck'

const route = useRoute()
const router = useRouter()
const submission = ref({})
const submitting = ref(false)
const checkingPlagiarism = ref(false)
const plagiarismResult = ref<PlagiarismResult | null>(null)

const gradingForm = ref({
  score: 0,
  comment: ''
})

const formatDate = (date: string) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm')
}

const loadSubmission = async () => {
  try {
    const { data } = await fetch(`/api/assignments/submissions/${route.params.assignmentId}`).then(res => res.json())
    submission.value = data
  } catch (error) {
    ElMessage.error('获取作业提交信息失败')
  }
}

const downloadFile = (file) => {
  window.open(file.url, '_blank')
}

const submitGrade = async () => {
  if (!gradingForm.value.comment.trim()) {
    ElMessage.warning('请输入评语')
    return
  }

  submitting.value = true
  try {
    await fetch(`/api/assignments/submissions/${route.params.assignmentId}/grade`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(gradingForm.value)
    })
    ElMessage.success('评分提交成功')
    router.push('/teacher/assignments/submissions')
  } catch (error) {
    ElMessage.error('评分提交失败')
  } finally {
    submitting.value = false
  }
}

const downloadAllAttachments = async () => {
  try {
    const zip = new JSZip()
    const attachments = submission.value.attachments

    // 创建进度提示
    const loading = ElMessage({
      message: '正在准备下载...',
      duration: 0,
      type: 'info'
    })

    // 下载所有文件并添加到zip
    const downloadPromises = attachments.map(async (file) => {
      const response = await fetch(file.url)
      const blob = await response.blob()
      zip.file(file.name, blob)
    })

    await Promise.all(downloadPromises)

    // 生成zip文件
    const zipBlob = await zip.generateAsync({ type: 'blob' })
    const fileName = `作业附件_${submission.value.studentName}_${format(new Date(), 'yyyyMMdd')}.zip`
    saveAs(zipBlob, fileName)

    loading.close()
    ElMessage.success('下载成功')
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

const checkPlagiarism = async () => {
  checkingPlagiarism.value = true
  try {
    const result = await checkPlagiarism(route.params.assignmentId as string)
    plagiarismResult.value = result
  } catch (error) {
    ElMessage.error('查重分析失败')
  } finally {
    checkingPlagiarism.value = false
  }
}

const getSimilarityClass = (similarity: number) => {
  if (similarity >= 0.7) return 'similarity-high'
  if (similarity >= 0.4) return 'similarity-medium'
  return 'similarity-low'
}

onMounted(() => {
  loadSubmission()
})
</script>

<style scoped>
.assignment-grading {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.student-info {
  display: flex;
  gap: 20px;
  color: #666;
}

.submission-content {
  margin-bottom: 30px;
}

.content-text {
  margin: 10px 0;
  white-space: pre-wrap;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.attachments {
  margin-top: 20px;
}

.attachments h4 {
  margin-bottom: 10px;
}

.attachments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.plagiarism-result {
  margin-bottom: 20px;
}

.matched-submissions {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.matched-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.match-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.matched-content {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
}

.matched-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.similarity-high {
  color: #f56c6c;
  font-weight: bold;
}

.similarity-medium {
  color: #e6a23c;
  font-weight: bold;
}

.similarity-low {
  color: #67c23a;
  font-weight: bold;
}
</style>

